package com.fw.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fw.config.Constants;
import com.fw.exception.ActionException;
import com.fw.exception.RenderException;
import com.fw.handler.Handler;
import com.fw.log.ActionLogger;
import com.fw.log.Logger;
import com.fw.render.Render;
import com.fw.render.RenderFactory;

public final class ActionHandler extends Handler {
	private static final Logger LOGGER = Logger.getLogger(ActionHandler.class);
	private static final RenderFactory renderFactory = RenderFactory.me();
	private final boolean devMode;
	private final ActionMapping actionMapping;

	public ActionHandler(ActionMapping actionMapping, Constants constants) {
		this.actionMapping = actionMapping;
		this.devMode = constants.getDevMode();
	}

	/**
	 * handle
	 * 1: Action action = actionMapping.getAction(target)
	 * 2: new ActionInvocation(...).invoke()
	 * 3: render(...)
	 */
	public final void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		if (target.indexOf(".") != -1) {
			return ;
		}
		
		isHandled[0] = true;
		String[] urlPara = {null};
		Action action = actionMapping.getAction(target, urlPara);
		
		//404
		if (action == null) {
			if (LOGGER.isWarnEnabled()) {
				String qs = request.getQueryString();
				LOGGER.warn("404 Action Not Found: " + (qs == null ? target : target + "?" + qs));
			}
			renderFactory.getErrorRender(404).setContext(request, response).render();
			return ;
		}

		try {
			Controller controller = action.getControllerClass().newInstance();
			controller.init(request, response, urlPara[0]);
			
			if (devMode) {
				boolean isMultipartRequest = ActionLogger.reportCommonRequest(controller, action);
				new ActionInvocation(action, controller).invoke();
				if (isMultipartRequest) {
					ActionLogger.reportMultipartRequest(controller, action);
				}
			} else {
				new ActionInvocation(action, controller).invoke();
			}
			
			Render render = controller.getRender();
			if (render instanceof ActionRender) {
				String actionUrl = ((ActionRender)render).getActionUrl();
				if (target.equals(actionUrl)) {
					throw new RuntimeException("The forward action url is the same as before.");
				} else {
					handle(actionUrl, request, response, isHandled);
				}
				return;
			}
			
			if (render == null) {
				render = renderFactory.getDefaultRender(action.getViewPath() + action.getMethodName());
			}
			render.setContext(request, response, action.getViewPath()).render();
		} catch (RenderException e) {
			if (LOGGER.isErrorEnabled()) {
				String qs = request.getQueryString();
				LOGGER.error(qs == null ? target : target + "?" + qs, e);
			}
		} catch (ActionException e) {
			int errorCode = e.getErrorCode();
			if (errorCode == 404 && LOGGER.isWarnEnabled()) {
				String qs = request.getQueryString();
				LOGGER.warn("404 Not Found: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 401 && LOGGER.isWarnEnabled()) {
				String qs = request.getQueryString();
				LOGGER.warn("401 Unauthorized: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 403 && LOGGER.isWarnEnabled()) {
				String qs = request.getQueryString();
				LOGGER.warn("403 Forbidden: " + (qs == null ? target : target + "?" + qs));
			} else if (LOGGER.isErrorEnabled()) {
				String qs = request.getQueryString();
				LOGGER.error(qs == null ? target : target + "?" + qs, e);
			}
			e.getErrorRender().setContext(request, response).render();
		} catch (Exception e) {
			if (LOGGER.isErrorEnabled()) {
				String qs = request.getQueryString();
				LOGGER.error(qs == null ? target : target + "?" + qs, e);
			}
			renderFactory.getErrorRender(500).setContext(request, response).render();
		}
	}
	
}
